"""主程序入口"""
import sys
import logging
import threading
from PyQt6.QtWidgets import QApplication

from chatai.ui.config_window import ConfigWindow
from chatai.core.chat import ChatBot
from chatai.utils.logger import setup_logger

def main():
    """主程序入口函数"""
    # 设置日志
    logger = setup_logger()
    
    # 创建应用
    app = QApplication(sys.argv)
    window = ConfigWindow()
    window.show()

    # 创建ChatBot实例
    bot = None
    bot_thread = None

    def start_bot(config_dict):
        """启动聊天机器人
        
        Args:
            config_dict (dict): 配置字典
        """
        nonlocal bot, bot_thread
        try:
            bot = ChatBot(**config_dict)
            # 创建并启动线程
            bot_thread = threading.Thread(target=bot.run, daemon=True)
            bot_thread.start()
        except Exception as e:
            logger.error(f"程序出错: {str(e)}")
            if bot:
                bot.stop()

    def stop_bot():
        """停止聊天机器人"""
        nonlocal bot, bot_thread
        if bot:
            bot.stop()
            if bot_thread and bot_thread.is_alive():
                bot_thread.join(timeout=2.0)  # 等待线程结束
            bot = None
            bot_thread = None

    # 连接信号
    window.program_started.connect(lambda: start_bot(window.get_config()))
    window.program_stopped.connect(stop_bot)

    # 在应用退出时确保清理资源
    app.aboutToQuit.connect(stop_bot)

    sys.exit(app.exec())

if __name__ == "__main__":
    main()